//
//  ConNewAllClubVc.m
//  Shengzhuli
//
//  Created by FXGuo on 2018/1/10.
//  Copyright © 2018年 kamangkeji. All rights reserved.
//

#import "ConNewAllClubVc.h"
#import "NewClubCell.h"
#import <Masonry.h>
#import "NewHomeNetwork.h"
#import "MBProgressHUD+MJ.h"
#import <MJRefresh.h>
#import "ConNewClubDetailVc.h"
#import <SDWebImageManager.h>
#import "SZLAccountHelper.h"
#import "SingleNetService.h"
#import "SZLTabBarViewController.h"

@interface ConNewAllClubVc ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,assign) NSInteger page;
@property (nonatomic,strong) NSMutableArray *clubLists;

@end

@implementation ConNewAllClubVc

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"推荐俱乐部";
    [self setUpTableView];
    self.page = 1;
    [self.tableView.mj_header beginRefreshing];
    self.tableView.mj_footer.hidden = YES;
}
- (void)setUpTableView
{
    [self.view addSubview:self.tableView];
}
#pragma ----------------tableView-----------------------------------
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 5;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return [[UIView alloc]init];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.clubLists.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 25+160*ScreenW/750;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NewClubCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([NewClubCell class])];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = self.clubLists[indexPath.row];
    cell.focusClick = ^(ClubModel *model) {
        [self addFocus:model];
    };
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ConNewClubDetailVc *detailVc = [[ConNewClubDetailVc alloc]init];
    ClubModel *model = self.clubLists[indexPath.row];
    detailVc.ID = model.ID;
    detailVc.focusClick = ^{
        [self.clubLists removeAllObjects];
        [self getClubList];
    };
    [self.navigationController pushViewController:detailVc animated:YES];
}
- (void)addFocus:(ClubModel *)model
{
    if (![SZLAccountHelper shouldLogin]) {
        NSMutableDictionary *parame = [NSMutableDictionary dictionary];
        parame[@"token"] = [SZLAccountHelper shareInstance].token;
        parame[@"clubId"] = @(model.ID);
        [self showWaiter];
        [SingleNetService addFocusParame:parame response:^(BOOL success, NSString *msg) {
            [self hideWaiter];
            if (success) {
                [self showOnlyText:@"关注成功"];
                model.keepStatus = 1;
                [self.tableView reloadData];
            }else {
                [MBProgressHUD showError:msg];
                if ([msg isEqualToString:NoLoginError]) {
                    [self.navigationController popToRootViewControllerAnimated:YES];
                    SZLTabBarViewController *barVc = (SZLTabBarViewController*)[UIApplication sharedApplication].keyWindow.rootViewController;
                    barVc.selectedIndex = 0;
                    [SZLAccountHelper clearAlreadyInfo];
                    [SZLAccountHelper shouldLogin];
                }
            }
        }];
    }
}
//俱乐部列表
- (void)getClubList
{
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"pageNo"] = @"1";
    if ([SZLAccountHelper isAlreadyLogin]) {
        parame[@"token"] = [SZLAccountHelper shareInstance].token;
    }
    [NewHomeNetwork getClubListWithParame:parame response:^(BOOL success, NSString *msg, NSArray *lists) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        [self hideNoDataLab];
        if (success) {
            self.tableView.mj_footer.hidden = (lists.count < 20);
            if (self.page == 1&&lists.count == 0) {
                [self showNoDataLab:self.tableView range:CGRectMake(0, (ScreenH-153)*0.5, ScreenW, 20) title:@"暂无数据"];
                return ;
            }
            [self.clubLists addObjectsFromArray:lists];
            //下载图片做测试
//            [self downloadImgs:lists];
            [self.tableView reloadData];
        }else {
            [MBProgressHUD showError:msg toView:self.view];
        }
    }];
}
- (void)downloadImgs:(NSArray *)arr
{
    dispatch_group_t group = dispatch_group_create();
    for (ClubModel *model in arr) {
        dispatch_group_enter(group);
        [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:model.clubLogo] options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
            if (finished) {
                [self.tableView reloadData];
                dispatch_group_leave(group);
            }
        }];
    }
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        //一次获取cell显示图片
        for (NSInteger i=0; i<arr.count; i++) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                ClubModel *model = arr[i];
                NewClubCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
                cell.imgStr = model.clubLogo;
            });
        }
    });
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH-SafeAreaTopHeight-SafeAreaBottomHeight)];
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([NewClubCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([NewClubCell class])];
        _tableView.backgroundColor = [UIColor colorWithHexString:@"#EFEFF4"];
        _tableView.separatorInset = UIEdgeInsetsMake(0, 10, 0, 0);
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.tableFooterView = [[UIView alloc]init];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            self.page = 1;
            [self.clubLists removeAllObjects];
            [self getClubList];
        }];
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            self.page++;
            [self getClubList];
        }];
    }
    return _tableView;
}
- (NSMutableArray *)clubLists
{
    if (!_clubLists) {
        _clubLists = [NSMutableArray array];
    }
    return _clubLists;
}


@end
